package com.cloudinnov.controller.api;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.quartz.CronScheduleBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudinnov.logic.JobTaskLogic;
import com.cloudinnov.task.model.ScheduleJob;
import com.cloudinnov.utils.support.RetObj;
import com.cloudinnov.utils.support.spring.SpringUtils;

/**
 * @author chengning
 * @date 2016年2月23日下午4:05:47
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Controller
@RequestMapping("/webapi/task")
public class TaskJobController extends BaseController {
	// 日志记录器
	public final Logger log = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private JobTaskLogic jobTaskLogic;

	@RequestMapping(value = "taskList", method = RequestMethod.GET)
	public void taskList(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Map<String, Object> map = new HashMap<>();
		String returnData = "";
		List<ScheduleJob> taskList = jobTaskLogic.getAllTask();
		map.put("list", taskList);
		returnData = returnJsonAllRequest(request, SUCCESS, map);
		response.getWriter().println(returnData);
	}
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public RetObj taskList(HttpServletRequest request, ScheduleJob scheduleJob) {
		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		try {
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
		} catch (Exception e) {
			retObj.setMsg("cron表达式有误，不能被解析！");
			return retObj;
		}
		Object obj = null;
		try {
			if (StringUtils.isNotBlank(scheduleJob.getSpringId())) {
				obj = SpringUtils.getBean(scheduleJob.getSpringId());
			} else {
				Class clazz = Class.forName(scheduleJob.getBeanClass());
				obj = clazz.newInstance();
			}
		} catch (Exception e) {
			// do nothing.........
		}
		if (obj == null) {
			retObj.setMsg("未找到目标类！");
			return retObj;
		} else {
			Class clazz = obj.getClass();
			Method method = null;
			try {
				method = clazz.getMethod(scheduleJob.getMethodName(), null);
			} catch (Exception e) {
				// do nothing.....
			}
			if (method == null) {
				retObj.setMsg("未找到目标方法！");
				return retObj;
			}
		}
		try {
			jobTaskLogic.addTask(scheduleJob);
		} catch (Exception e) {
			e.printStackTrace();
			retObj.setFlag(false);
			retObj.setMsg("保存失败，检查 name group 组合是否有重复！");
			return retObj;
		}
		retObj.setFlag(true);
		return retObj;
	}
	@RequestMapping(value = "changeJobStatus", method = RequestMethod.POST)
	@ResponseBody
	public RetObj changeJobStatus(HttpServletRequest request, Long jobId, String cmd) {
		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		jobTaskLogic.changeStatus(jobId, cmd);
		retObj.setFlag(true);
		return retObj;
	}
	@RequestMapping(value = "updateCron", method = RequestMethod.POST)
	@ResponseBody
	public RetObj updateCron(HttpServletRequest request, Long jobId, String cron) {
		RetObj retObj = new RetObj();
		retObj.setFlag(false);
		try {
			@SuppressWarnings("unused")
			CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
		} catch (Exception e) {
			retObj.setMsg("cron表达式有误，不能被解析！");
			return retObj;
		}
		jobTaskLogic.updateCron(jobId, cron);
		retObj.setFlag(true);
		return retObj;
	}
}
